package com.zae.config;

import com.zae.pojo.Configuration;
import com.zae.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
/**
 * 解析mapper.xml数据存放到javaBean中
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration){
        this.configuration = configuration;
    }

    public void parasMapper(InputStream mapperInputStream) throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(mapperInputStream);
        //获取根标签的数据-mapper
        Element rootElement = document.getRootElement();
        //获取命名空间
        String namespace = rootElement.attributeValue("namespace");
        //获取所有的select标签的内容
        List<Element> elementList = rootElement.selectNodes("//select");
        for (Element element : elementList) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();
            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            mapperStatement.setResultType(resultType);
            mapperStatement.setParamterType(paramterType);
            mapperStatement.setSql(sql);
            String key = namespace+"."+id;
            configuration.getMapperStatementMap().put(key,mapperStatement);
        }
    }
}
